package com.qiniu;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

public class SimpleUpload {

	/**
	 * 主函数：程序入口，测试功能
	 * @param args
	 * @throws QiniuException
	 */
	public static void main(String[] args) throws QiniuException {

		Configuration cfg=new Configuration(Zone.autoZone());
		UploadManager uploadManager = new  UploadManager(cfg);

		Auth auth = Auth.create(AccountMgr.ACCESS_KEY, AccountMgr.SECRET_KEY);

		String uploadToken=auth.uploadToken(AccountMgr.BUCKET_NAME);

		// 上传文件的路径，因为在Mac下，所以路径和windows下不同
		String filePath = "/Users/houzhong/Downloads/testimg/m3.jpg";
		// 上传到七牛后保存的文件名
		String key = System.currentTimeMillis()+".jpg";
		try {
			Response response = uploadManager.put(filePath, key, uploadToken);
			//解析上传成功的结果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			System.out.println(putRet.key);
			System.out.println(putRet.hash);
		} catch (QiniuException ex) {
			Response r = ex.response;
			System.err.println(r.toString());
			try {
				System.err.println(r.bodyString());
			} catch (QiniuException ex2) {
				//ignore
			}
		}

		// 要上传的空间
		// 这里的filepath可以直接替换成File如下注释所示
		// File file=new File(filePath);
		// new SimpleUpload().upload(file, key, bucketName);
		//new SimpleUpload().upload(filePath, key, AccountMgr.BUCKET_NAME);
	}

}
